﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Follow.Business;
using System.Windows.Forms;

namespace Follow.Cadastros
{
    public partial class FollowUp : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Session["idUsuario"] == null)
                {
                    Response.Redirect("../Default.aspx");
                }
                else
                {
                    Common.ValidaPermissoes valida = new Common.ValidaPermissoes();
                    bool possuiPermissao = valida.validaPermissaoPorTela("Proposta", Convert.ToInt32(Session["idGrupoUsuario"]));

                    if (possuiPermissao == false)
                    {
                        Response.Redirect("../permissaoNegada.aspx");
                    }

                    if ((Request.QueryString["idProposta"] != null) && (Request.QueryString["idFollowUp"] != null))
                    {
                        idFollowUp.Value = Request.QueryString["idFollowUp"];
                        idProposta.Value = Request.QueryString["idProposta"];

                        PopulaStatus();
                        PopulaAlteracaoStatus();
                        
                        
                    }
                    else
                    {
                        PopulaStatus();
                        PopulaFollowUp();
                    }
                }
            }
        }

        private void PopulaFollowUp()
        {
            Model.Funcionario funcionario = new Model.Funcionario();
            Business.FuncionarioBO boFuncionario = new Business.FuncionarioBO();

            Model.Contato contato = new Model.Contato();
            ContatoBO boContato = new ContatoBO();

            if (boFuncionario.findByIdUsuario(Convert.ToInt32(Session["idUsuario"])) != null)
            {

                funcionario = boFuncionario.findByIdUsuario(Convert.ToInt32(Session["idUsuario"]));

                Business.ViewFollowBO bo = new Business.ViewFollowBO();

                gvFollowUp.DataSource = bo.findByFuncionario(funcionario.IDFuncionario.ToString(), funcionario.TipoFunc, ddlPesquisaStatus.SelectedIndex);
                gvFollowUp.DataBind();

            }

            else
            {
                contato = boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"]));
                btnIncluir.Visible = false;

                Business.ViewFollowBO bo = new Business.ViewFollowBO();

                gvFollowUp.DataSource = bo.findByContato(contato.IDCliente, ddlPesquisaStatus.SelectedIndex);

                gvFollowUp.DataBind();
            }
        }

        protected void btnIncluir_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Cadastros/CadastroProposta.aspx");
        }

        protected void btnPesquisa_Click(object sender, EventArgs e)
        {
            this.PopulaFollowUp();
        }

        protected void gvFollowUp_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                LinkButton lkbAlterarStatus = (LinkButton)e.Row.FindControl("lkbAlterarStatus");
                lkbAlterarStatus.CommandArgument = DataBinder.Eval(e.Row.DataItem, "IDFollowUp").ToString() + ";" + DataBinder.Eval(e.Row.DataItem, "IDProposta").ToString();

                LinkButton lkbExcluirProposta = (LinkButton)e.Row.FindControl("lkbExcluirProposta");
                lkbExcluirProposta.CommandArgument = DataBinder.Eval(e.Row.DataItem, "IDFollowUp").ToString() + ";" + DataBinder.Eval(e.Row.DataItem, "IDProposta").ToString();

                LinkButton lkbAlterarProposta = (LinkButton)e.Row.FindControl("lkbAlterarProposta");
                lkbAlterarProposta.CommandArgument = DataBinder.Eval(e.Row.DataItem, "IDFollowUp").ToString() + ";" + DataBinder.Eval(e.Row.DataItem, "IDProposta").ToString();

                LinkButton lkbDetalhesProposta = (LinkButton)e.Row.FindControl("lkbDetalhesProposta");
                lkbDetalhesProposta.CommandArgument = DataBinder.Eval(e.Row.DataItem, "IDFollowUp").ToString() + ";" + DataBinder.Eval(e.Row.DataItem, "IDProposta").ToString();


                System.Web.UI.WebControls.Label lblIdStatusFollow = (System.Web.UI.WebControls.Label)e.Row.FindControl("lblIdStatusFollow");

                Image imgStatus = (Image)e.Row.FindControl("imgStatus");

                Model.Contato contato = new Model.Contato();
                ContatoBO boContato = new ContatoBO();
               

                switch (Convert.ToInt32(lblIdStatusFollow.Text))
                {
                    //Nova
                    case 1:
                        if (boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"])) != null)
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = false;
                            lkbDetalhesProposta.Visible = true;
                        }
                        else
                        {
                        lkbExcluirProposta.Visible = true;
                        lkbAlterarProposta.Visible = true;
                        lkbAlterarStatus.Visible = true;
                        lkbDetalhesProposta.Visible = true;
                        }


                        imgStatus.ImageUrl = "~/images/1 - Nova.png";
                        imgStatus.ToolTip = "Nova";

                        break;
                    //Aguardando Aprovação
                    case 2:
                        if (boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"])) != null)
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = true;
                            lkbDetalhesProposta.Visible = true;

                        }

                        else
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = true;
                            lkbDetalhesProposta.Visible = true;
                        }
                            
                         imgStatus.ToolTip = "Aguardando Aprovação";
                        imgStatus.ImageUrl = "~/images/2 - Aguardando.png";
                        break;
                    //Retornado para alteração
                    case 3:
                        if (boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"])) != null)
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = false;
                            lkbDetalhesProposta.Visible = true;
                        }
                        else
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = true;
                            lkbAlterarStatus.Visible = true;
                            lkbDetalhesProposta.Visible = true;
                        }
                        imgStatus.ImageUrl = "~/images/3 - Retornado.png";
                        imgStatus.ToolTip = "Retornado para alteração";
                        break;
                    //Aprovada
                    case 4:
                        if (boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"])) != null)
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = false;
                            lkbDetalhesProposta.Visible = true;
                        }
                        else
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = true;
                            lkbDetalhesProposta.Visible = true;
                        }
                            
                        imgStatus.ImageUrl = "~/images/4 - Aprovada.png";
                        imgStatus.ToolTip = "Aprovada";
                        break;
                    //Reprovada
                    case 5:
                        if (boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"])) != null)
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = false;
                            lkbDetalhesProposta.Visible = true;
                        }

                        else
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = false;
                            lkbDetalhesProposta.Visible = true;
                        }
                        imgStatus.ImageUrl = "~/images/5 - Reprovada.png";
                        imgStatus.ToolTip = "Reprovada";
                        break;

                    //Concluída
                    case 6:
                        if (boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"])) != null)
                        {
                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = false;
                            lkbDetalhesProposta.Visible = true;
                        }
                        else
                        {

                            lkbExcluirProposta.Visible = false;
                            lkbAlterarProposta.Visible = false;
                            lkbAlterarStatus.Visible = false;
                            lkbDetalhesProposta.Visible = true;
                        }
                        imgStatus.ImageUrl = "~/images/6 - Concluída.png";
                        imgStatus.ToolTip = "Concluída";
                        break;
                }

                               
            }
        }

        protected void gvFollowUp_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string[] ids = e.CommandArgument.ToString().Split(';');

            idFollowUp.Value = ids[0];
            idProposta.Value = ids[1];

            if (e.CommandName == "AlterarStatus")
            {
                Title = "Alterar Status";
                PopulaAlteracaoStatus();
            }
            else if (e.CommandName == "DeletarProposta")
            {
                if (System.Windows.Forms.MessageBox.Show("Tem certeza que deseja excluir?", "Excluir", MessageBoxButtons.OKCancel,
                    MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.ServiceNotification) ==
                    System.Windows.Forms.DialogResult.OK)
                {

                    Int32 id = 0;
                    try
                    {
                        id = Convert.ToInt32(idProposta.Value);
                    }
                    catch
                    {
                        return;
                    }
                    Business.PropostaBO bo = new Business.PropostaBO();
                    try
                    {
                        bo.deleteProposta(id, Convert.ToInt32(Session["idUsuario"]));

                        divMsg1.Visible = true;
                        divMsg1.Attributes["class"] = "isa_success";
                        lblMsg1.Text = "Proposta excluído com sucesso!";

                        this.PopulaFollowUp();
                    }
                    catch (Exception ex)
                    {
                        divMsg1.Visible = true;
                        divMsg1.Attributes["class"] = "isa_error";
                        lblMsg1.Text = "Erro ao excluir proposta: " + ex.Message;
                    }
                }

            }
            else if (e.CommandName == "AlterarProposta")
            {
                Response.Redirect("~/Cadastros/CadastroProposta.aspx?idFollowUp=" + idFollowUp.Value + "&idProposta=" + idProposta.Value);
            }
            else if (e.CommandName == "VerDetalhes")
            {
                Session["idProposta"] = idProposta.Value;

                Response.Redirect("~/Cadastros/DetalheProposta.aspx");
            }
        }

        private void PopulaAlteracaoStatus()
        {
            Business.StatusFollowBO bo = new Business.StatusFollowBO();

            ddlStatus.DataSource = bo.findByStatusAtual(Convert.ToInt32(idProposta.Value), Convert.ToInt32(idFollowUp.Value));
            ddlStatus.DataTextField = "DescricaoStatus";
            ddlStatus.DataValueField = "IDStatus";
            ddlStatus.DataBind();

            ddlStatus.Items.Insert(0, "Selecione..");

            Business.ViewFollowUpPropostaBO view = new Business.ViewFollowUpPropostaBO();

            gvHistoricoStatus.DataSource = view.findAll(idProposta.Value);
            gvHistoricoStatus.DataBind();
            int proposta = Convert.ToInt32(idProposta.Value);
            PopulaFollowUpProposta(proposta);
            mvFollowUp.ActiveViewIndex = 1;
        }

        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            Model.Funcionario funcionario = new Model.Funcionario();
            Business.FuncionarioBO boFuncionario = new Business.FuncionarioBO();
            Model.Contato contato = new Model.Contato();
            Business.ContatoBO boContato = new Business.ContatoBO();

            if (boFuncionario.findByIdUsuario(Convert.ToInt32(Session["idUsuario"])) != null)
            {
                funcionario = boFuncionario.findByIdUsuario(Convert.ToInt32(Session["idUsuario"]));

                Business.FollowUpBO followBO = new Business.FollowUpBO();
                Model.FollowUp follow = new Model.FollowUp();

                follow.IDFuncionario = funcionario.IDFuncionario;
                follow.IDProposta = Convert.ToInt32(idProposta.Value);
                follow.IDStatus = Convert.ToInt32(ddlStatus.SelectedValue);
                follow.ObsFollowUp = txtObservacao.Text;
                follow.DataFollowUp = DateTime.Now;

                followBO.save(follow, Convert.ToInt32(Session["idUsuario"]));
                divMsg2.Visible = true;
                divMsg2.Attributes["class"] = "isa_success";
                lblMsg2.Text = "Follow Up salvo com sucesso!";
            }

            else
            {
                contato = boContato.findByUsuarioContato(Convert.ToInt32(Session["idUsuario"]));
                Business.FollowUpBO followBO = new Business.FollowUpBO();
                Model.FollowUp follow = new Model.FollowUp();

                follow.IDContato = contato.IDContato;
                follow.IDProposta = Convert.ToInt32(idProposta.Value);
                follow.IDStatus = Convert.ToInt32(ddlStatus.SelectedValue);
                follow.ObsFollowUp = txtObservacao.Text;
                follow.DataFollowUp = DateTime.Now;

                followBO.save(follow, Convert.ToInt32(Session["idUsuario"]));
                divMsg2.Visible = true;
                divMsg2.Attributes["class"] = "isa_success";
                lblMsg2.Text = "Follow Up salvo com sucesso!";
            }
            
            txtObservacao.Text = "";
            ddlStatus.SelectedIndex = 0;

            PopulaFollowUp();

            mvFollowUp.ActiveViewIndex = 0;
        }

        protected void btnCancelar_Click(object sender, EventArgs e)
        {

            txtObservacao.Text = "";
            ddlStatus.SelectedIndex = 0;

            mvFollowUp.ActiveViewIndex = 0;
        }

        private void PopulaFollowUpProposta(int proposta)
        {
            Business.ViewFollowUpPropostaBO view = new Business.ViewFollowUpPropostaBO();
            gvHistoricoStatus.DataSource = view.findAll(idProposta.Value);
            gvHistoricoStatus.DataBind();

            if (gvHistoricoStatus.Rows.Count == 0)
                gvHistoricoStatus.Visible = true;
        }


        protected void gvFollowUp_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvFollowUp.PageIndex = e.NewPageIndex;
            gvFollowUp.DataBind();
            PopulaFollowUp();
        }

        private void PopulaStatus()
        {
            StatusFollowBO bo = new StatusFollowBO();
            ddlPesquisaStatus.DataSource = bo.findAll();
            ddlPesquisaStatus.DataValueField = "idstatus";
            ddlPesquisaStatus.DataTextField = "descricaostatus";
            ddlPesquisaStatus.DataBind();
            ddlPesquisaStatus.Items.Insert(0, "Todos");
        }

 
    }
}